package com.iculture;

import helper.FBHelper;

import java.util.ArrayList;
import java.util.Hashtable;
import org.json.JSONArray;
import org.json.JSONException;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.widget.WebDialog;
import com.matchcalendar.R;
import activities.AddMatchGroupActivity;
import activities.GlobalActivity;
import activities.MatchActivity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import android.widget.Toast;

public class FirstJsonExUrlActivity extends GlobalActivity {
	/** Called when the activity is first created. */
	private ImageButton search_button;
	private ImageButton favorite_button;
	private Spinner activity_spinner;
	private int activity_value = 1;
	private ProgressDialog progDlg;
	private Dialog myDialog;
	private Button share;
	private Button match;
	private Button ticket;
	private Button favorite;
	private ImageView cancel;
	private TextView title;
	private TextView time;
	private TextView location;
	private TextView locationName;
	private TextView description;
	private String myID;
	private String send_UID;
	private ArrayList<Activity_DataStructure> DataList = new ArrayList<Activity_DataStructure>();
	private final int MATCH_REQUEST_CODE = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);
		initGlobalView();
		getButtonActivity().setEnabled(false);
		getButtonActivity().setBackgroundResource(R.color.gray5);
		setupViewComponent();
		setupSpnner();
		loader();
	}

	private void setupViewComponent() {
		activity_spinner = (Spinner) findViewById(R.id.activity_spnner);
		search_button = (ImageButton) findViewById(R.id.imageButton1);
		search_button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent it = new Intent(FirstJsonExUrlActivity.this,
						SearchActivity.class);
				startActivity(it);
			}
		});
		favorite_button=(ImageButton) findViewById(R.id.imageButton2);
		favorite_button.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent it = new Intent(FirstJsonExUrlActivity.this,
						FavoriteListActivity.class);
				startActivity(it);
			}
		});

		// getJsonbtn = (Button) findViewById(R.id.getJsonbtn);
		// getJsonbtn.setOnClickListener(getJsonbtnOnClick);
		// mBtnProgDlg.setOnClickListener(btnProgDlgOnClkLis);
	}

	private void setupSpnner() {
		ArrayAdapter<CharSequence> activity_list = ArrayAdapter
				.createFromResource(this, R.array.activity_array,
						android.R.layout.simple_spinner_dropdown_item);
		activity_spinner.setAdapter(activity_list);
		activity_spinner.setOnItemSelectedListener(spnActItemSelLis);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Log.v("ola_log", "landscape");
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			Log.v("ola_log", "portrait");
		}
	}

	private Spinner.OnItemSelectedListener spnActItemSelLis = new Spinner.OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView parent, View v, int position,
				long id) {
			// 1音樂,5獨立音樂,6展覽,2戲劇,3舞蹈,4親子,17演唱會
			int[] activity_parse = { 1, 5, 6, 2, 3, 4, 17 };
			// System.out.println(activity_value);
			if (activity_value != activity_parse[parent
					.getSelectedItemPosition()]) {
				activity_value = activity_parse[parent
						.getSelectedItemPosition()];
				loader();
			}
		}

		@Override
		public void onNothingSelected(AdapterView parent) {
			// TODO Auto-generated method stub

		}
	};

	/*
	 * private Button.OnClickListener getJsonbtnOnClick = new
	 * Button.OnClickListener() {
	 * 
	 * @Override public void onClick(View v) { loader(); } };
	 */

	private void loader() {
		progDlg = new ProgressDialog(FirstJsonExUrlActivity.this);
		progDlg.setMessage(getString(R.string.loadingtxt));
		progDlg.setIcon(android.R.drawable.ic_dialog_info);
		progDlg.setCancelable(false);
		progDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDlg.setMax(100);
		progDlg.show();
		new Thread(new Runnable() {
			public void run() {
				executeAsyncTask();

			}
		}).start();
	}

	private class GetDataAyncTask extends
			AsyncTask<Hashtable<String, String>, Void, String> {

		@Override
		protected String doInBackground(Hashtable<String, String>... params) {
			Hashtable ht = params[0];

			String json = HelperHttp.getJSONResponseFromURL("output.php", ht);
			if (json != null) {
				Activity_DataStructure data = new Activity_DataStructure();
				DataList = data.parseJsonString(json);
				progDlg.setProgress(100);
				progDlg.cancel();
			} else {
				return "Invalid Param";
			}
			return "SUCCESS";
		}

		@Override
		protected void onPostExecute(String result) {

			if (result == "SUCCESS") {
				/*Toast.makeText(FirstJsonExUrlActivity.this, "資料載入成功!",
						Toast.LENGTH_SHORT).show();*/
				final DataArrayAdapter adapter = new DataArrayAdapter(
						FirstJsonExUrlActivity.this, R.id.title, DataList);
				ListView listv = (ListView) findViewById(R.id.lv);
				listv.setAdapter(adapter);
				listv.setScrollingCacheEnabled(false);// 解決殘影問題
				listv.setDivider(new ColorDrawable()); // listview間隔顏色
				listv.setDividerHeight(5); // listview間距
				listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView parent, View view,
							final int position, long id) {
						/*
						 * Toast.makeText(FirstJsonExUrlActivity.this,
						 * adapter.getItem(position).title,
						 * Toast.LENGTH_SHORT).show();
						 */
						myDialog = new Dialog(FirstJsonExUrlActivity.this,
								R.style.PauseDialog);
						myDialog.setContentView(R.layout.activity_dialog_layout);
						myDialog.setTitle(R.string.activity_detail);
						title = (TextView) myDialog
								.findViewById(R.id.dialog_title);
						time = (TextView) myDialog
								.findViewById(R.id.dialog_time);
						location = (TextView) myDialog
								.findViewById(R.id.dialog_location);
						locationName = (TextView) myDialog
								.findViewById(R.id.dialog_locationName);
						description = (TextView) myDialog
								.findViewById(R.id.dialog_description);
						share = (BgButton) myDialog
								.findViewById(R.id.btn_share);
						match = (BgButton) myDialog
								.findViewById(R.id.btn_match);
						ticket = (BgButton) myDialog
								.findViewById(R.id.btn_ticket);
						favorite = (BgButton) myDialog
								.findViewById(R.id.btn_love);
						cancel = (ImageView) myDialog
								.findViewById(R.id.dialog_cancel);

						title.setText("活動名稱:\n"
								+ adapter.getItem(position).title + "\n");
						time.setText("活動時間:\n"
								+ adapter.getItem(position).startEndTime + "\n");
						locationName.setText("活動地點:\n"
								+ adapter.getItem(position).locationName + "\n");
						location.setText("活動地址:\n"
								+ adapter.getItem(position).location + "\n");
						if (adapter.getItem(position).showUnit.length() > 2) {
							location.append("\n表演單位:\n"
									+ adapter.getItem(position).showUnit + "\n");
						}

						description.setText("活動說明:\n"
								+ adapter.getItem(position).descriptionFilterHtml
								+ "\n");

						if (!adapter.getItem(position).webSales
								.contains("http")) {
							ticket.setText("無售票");
							ticket.setEnabled(false);
						}

						cancel.setOnClickListener(new ImageView.OnClickListener() {
							public void onClick(View v) {
								myDialog.cancel();
							}
						});

						Window dialogWindow = myDialog.getWindow();
						WindowManager m = dialogWindow.getWindowManager();
						Display d = m.getDefaultDisplay();
						LayoutParams p = dialogWindow.getAttributes();

						// p.height = (int) (d.getHeight() * 1);
						p.width = (int) (d.getWidth() * 1);
						p.alpha = 1.0f;
						dialogWindow.setAttributes(p);

						share.setOnClickListener(new Button.OnClickListener() {
							public void onClick(View v) {
								/*
								 * Intent it = new
								 * Intent(FirstJsonExUrlActivity.this,
								 * SearchActivity.class); startActivity(it);
								 */
								System.out.println("UID===========>"+adapter.getItem(position).UID);
								publishFeedDialog(
										adapter.getItem(position).title,
										adapter.getItem(position).imageUrl,
										"http://cloud.culture.tw/frontsite/inquiry/contentListAction.do?method=doFindContent&subMenuId=401&id="
												+ adapter.getItem(position).UID,
										adapter.getItem(position).location,
										adapter.getItem(position).descriptionFilterHtml);
							}
						});
						ticket.setOnClickListener(new Button.OnClickListener() {
							public void onClick(View v) {
								Uri uri = Uri.parse(adapter.getItem(position).webSales);
								final Intent it = new Intent(
										Intent.ACTION_VIEW, uri);
								startActivity(it);

							}
						});
						match.setOnClickListener(new Button.OnClickListener() {
							public void onClick(View v) {
								Intent it = new Intent(FirstJsonExUrlActivity.this, AddMatchGroupActivity.class);
                                Bundle bundle = new Bundle();
                                
                                bundle.putString("myFBID", getIntent().getExtras().getString("myFBID"));
                                bundle.putString("ACT_NAME",
                                                adapter.getItem(position).title);
                                bundle.putString("ACT_LOCATION",
                                                adapter.getItem(position).location);
                                bundle.putString("ACT_TIME",
                                                adapter.getItem(position).time);
                                bundle.putInt("comeFrom", 1);
                                it.putExtras(bundle);
                                startActivityForResult(it, MATCH_REQUEST_CODE);
							}
						});
						favorite.setOnClickListener(new Button.OnClickListener() {
							public void onClick(View v) {
								new GetMyIDFBHelper()
										.ensureSessionOpenAndDoSomething(FirstJsonExUrlActivity.this);
								send_UID=adapter.getItem(position).UID;
							}
						});

						myDialog.setCanceledOnTouchOutside(true);
						myDialog.show();
					}
				});

			} else {
			}
		}

	}

	private void publishFeedDialog(String title, String picture, String link,
			String location, String description) {
		try {
			Bundle params = new Bundle();
			params.putString("name", title);// title
			params.putString("picture",
					"http://cloud.culture.tw/frontsite/images/no-120.gif");
			params.putString("link", link);
			params.putString("caption", location);// caption
			params.putString("description", description);

			WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
					FirstJsonExUrlActivity.this, Session.getActiveSession(),
					params)).setOnCompleteListener(null).build();
			feedDialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class GetMyIDFBHelper extends FBHelper {
		private ProgressDialog proDialog;

		@Override
		protected void doAfterEnsureSessionOpen() {
			proDialog = ProgressDialog.show(FirstJsonExUrlActivity.this, "資料傳送中",
					"正在新增至我的最愛列表...");
			proDialog.setCancelable(false);
			fqlQuery("uid", "user", "uid = me()", null, null, null, null);
		}

		@Override
		protected void doAfterFqlQuery(Response response) {
			try {
				JSONArray dataJsonArr = response.getGraphObject()
						.getInnerJSONObject().getJSONArray("data");
				myID = dataJsonArr.getJSONObject(0).getString("uid");
				proDialog.cancel();
				//Toast.makeText(FirstJsonExUrlActivity.this, myID,Toast.LENGTH_SHORT).show();
			
				new Thread(new Runnable() {
					public void run() {
						executeAsyncTask2();

					}
				}).start();

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	private class SendFavorite extends
			AsyncTask<Hashtable<String, String>, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Hashtable<String, String>... params) {
			Hashtable ht = params[0];
			Boolean result=false;

			String json = HelperHttp.getJSONResponseFromURL("activity_favorite.php", ht);
			if (json != null) {
				if (json.contains("true")){
					result=true;
				}
				//progDlg.setProgress(100);
				//progDlg.cancel();
			} else {
				return false;
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {

			if (result == true) {
				Toast.makeText(FirstJsonExUrlActivity.this, "我的最愛加入成功!",
						Toast.LENGTH_SHORT).show();

			} else {
				Toast.makeText(FirstJsonExUrlActivity.this, "資料傳送發生錯誤!",
						Toast.LENGTH_SHORT).show();
			}
		}

	}

	private void executeAsyncTask() {
		Hashtable<String, String> ht = new Hashtable<String, String>();
		GetDataAyncTask async = new GetDataAyncTask();
		/*
		 * Bundle bundle=getIntent().getExtras();
		 * activity_value=bundle.getInt("ACT_VALUE");
		 */
		ht.put("type", String.valueOf(activity_value));// 設定json url搜尋參數
		// ht.put("category", "2");
		Hashtable[] ht_array = { ht };
		async.execute(ht_array);
	}
	
	private void executeAsyncTask2() {
		Hashtable<String, String> ht = new Hashtable<String, String>();
		SendFavorite async = new SendFavorite();

		ht.put("fbid", myID);
		ht.put("uid", send_UID);
		ht.put("action", "add");
		Hashtable[] ht_array = { ht };
		async.execute(ht_array);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case MATCH_REQUEST_CODE:
					Bundle bundle = new Bundle();
					Intent intent = new Intent(FirstJsonExUrlActivity.this, MatchActivity.class);
					
					bundle.putString("myFBID", getIntent().getExtras().getString("myFBID"));
					intent.putExtras(bundle);
					startActivity(intent);
					myDialog.cancel();
					FirstJsonExUrlActivity.this.finish();
			}
		}
	}
}